@namespace Oqtane.Modules.Admin.SystemInfo
@inherits ModuleBase
@inject ISystemService SystemService
@inject IInstallationService InstallationService
@inject IStringLocalizer<Index> Localizer
@inject IStringLocalizer<SharedResources> SharedLocalizer

<TabStrip>
    <TabPanel Name="Info" Heading="Info" ResourceKey="Info">
        <div class="container">
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="version" HelpText="Framework Version" ResourceKey="FrameworkVersion">Framework Version: </Label>
                <div class="col-sm-9">
                    <input id="version" class="form-control" @bind="@_version" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="clrversion" HelpText="Common Language Runtime Version" ResourceKey="CLRVersion">CLR Version: </Label>
                <div class="col-sm-9">
                    <input id="clrversion" class="form-control" @bind="@_clrversion" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="osversion" HelpText="Operating System Version" ResourceKey="OSVersion">OS Version: </Label>
                <div class="col-sm-9">
                    <input id="osversion" class="form-control" @bind="@_osversion" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="machinename" HelpText="Machine Name" ResourceKey="MachineName">Machine Name: </Label>
                <div class="col-sm-9">
                    <input id="machinename" class="form-control" @bind="@_machinename" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="ipaddress" HelpText="Server IP Address" ResourceKey="IPAddress">IP Address: </Label>
                <div class="col-sm-9">
                    <input id="ipaddress" class="form-control" @bind="@_ipaddress" readonly />
                </div>
            </div>
			<div class="row mb-1 align-items-center">
				<Label Class="col-sm-3" For="environment" HelpText="Environment name" ResourceKey="Environment">Environment: </Label>
				<div class="col-sm-9">
					<input id="environment" class="form-control" @bind="@_environment" readonly />
				</div>
			</div>
			<div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="contentrootpath" HelpText="Root Path" ResourceKey="ContentRootPath">Root Path: </Label>
                <div class="col-sm-9">
                    <input id="contentrootpath" class="form-control" @bind="@_contentrootpath" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="webrootpath" HelpText="Web Path" ResourceKey="WebRootPath">Web Path: </Label>
                <div class="col-sm-9">
                    <input id="webrootpath" class="form-control" @bind="@_webrootpath" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="servertime" HelpText="Server Date/Time (in UTC)" ResourceKey="ServerTime">Server Date/Time: </Label>
                <div class="col-sm-9">
                    <input id="servertime" class="form-control" @bind="@_servertime" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="tickcount" HelpText="Amount Of Time The Service Has Been Available And Operational" ResourceKey="TickCount">Service Uptime: </Label>
                <div class="col-sm-9">
                    <input id="tickcount" class="form-control" @bind="@_tickcount" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="workingset" HelpText="Memory Allocation Of Service (in MB)" ResourceKey="WorkingSet">Memory Allocation: </Label>
                <div class="col-sm-9">
                    <input id="workingset" class="form-control" @bind="@_workingset" readonly />
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="installationid" HelpText="The Unique Identifier For Your Installation" ResourceKey="InstallationId">Installation ID: </Label>
                <div class="col-sm-9">
                    <input id="installationid" class="form-control" @bind="@_installationid" readonly />
                </div>
            </div>
        </div>
        <br /><br />
        <ActionDialog Header="Restart Application" Message="Are You Sure You Wish To Restart The Application?" Action="Restart Application" Security="SecurityAccessLevel.Host" Class="btn btn-danger" OnClick="@(async () => await RestartApplication())" ResourceKey="RestartApplication" />
    </TabPanel>
    <TabPanel Name="Options" Heading="Options" ResourceKey="Options">
        <div class="container">
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="detailederrors" HelpText="Specify If Detailed Errors Are Enabled For Blazor. This Option Should Not Not Be Enabled In Production." ResourceKey="DetailedErrors">Detailed Errors? </Label>
                <div class="col-sm-9">
                    <select id="detailederrors" class="form-select" @bind="@_detailederrors">
                        <option value="true">@SharedLocalizer["True"]</option>
                        <option value="false">@SharedLocalizer["False"]</option>
                    </select>
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="logginglevel" HelpText="The Minimum Logging Level For The Event Log. This Option Can Be Used To Control The Volume Of Items Stored In Your Event Log." ResourceKey="LoggingLevel">Logging Level: </Label>
                <div class="col-sm-9">
                    <select id="logginglevel" class="form-select" @bind="@_logginglevel">
                        <option value="Trace">@Localizer["Trace"]</option>
                        <option value="Debug">@Localizer["Debug"]</option>
                        <option value="Information">@Localizer["Information"]</option>
                        <option value="Warning">@Localizer["Warning"]</option>
                        <option value="Error">@Localizer["Error"]</option>
                        <option value="Critical">@Localizer["Critical"]</option>
                        <option value="None">@Localizer["None"]</option>
                    </select>
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="notificationlevel" HelpText="The Minimum Logging Level For Which Notifications Should Be Sent To Host Users." ResourceKey="NotificationLevel">Notification Level: </Label>
                <div class="col-sm-9">
                    <select id="notificationlevel" class="form-select" @bind="@_notificationlevel">
                        <option value="Trace">@Localizer["Trace"]</option>
                        <option value="Debug">@Localizer["Debug"]</option>
                        <option value="Information">@Localizer["Information"]</option>
                        <option value="Warning">@Localizer["Warning"]</option>
                        <option value="Error">@Localizer["Error"]</option>
                        <option value="Critical">@Localizer["Critical"]</option>
                        <option value="None">@Localizer["None"]</option>
                    </select>
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="swagger" HelpText="Specify If Swagger Is Enabled For Your Server API" ResourceKey="Swagger">Swagger Enabled? </Label>
                <div class="col-sm-9">
                    <select id="swagger" class="form-select" @bind="@_swagger">
                        <option value="true">@SharedLocalizer["True"]</option>
                        <option value="false">@SharedLocalizer["False"]</option>
                    </select>
                </div>
            </div>
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="packageregistryurl" HelpText="Specify The Package Manager Service For Installing Modules, Themes, And Translations. If This Field Is Blank It Means The Package Manager Service Is Disabled For This Installation." ResourceKey="PackageManager">Package Manager: </Label>
                <div class="col-sm-9">
                    <input id="packageregistryurl" class="form-control" @bind="@_packageregistryurl" />
                </div>
            </div>
        </div>
        <br /><br />
        <button type="button" class="btn btn-success" @onclick="SaveConfig">@SharedLocalizer["Save"]</button>&nbsp;
        <a class="btn btn-primary" href="swagger/index.html" target="_new">@Localizer["Access.ApiFramework"]</a>&nbsp;
        <ActionDialog Header="Restart Application" Message="Are You Sure You Wish To Restart The Application?" Action="Restart Application" Security="SecurityAccessLevel.Host" Class="btn btn-danger" OnClick="@(async () => await RestartApplication())" ResourceKey="RestartApplication" />
    </TabPanel>
    <TabPanel Name="Log" Heading="Log" ResourceKey="Log">
        <div class="container">
            <div class="row mb-1 align-items-center">
                <Label Class="col-sm-3" For="log" HelpText="System log information for current day" ResourceKey="Log">Log: </Label>
                <div class="col-sm-9">
                    <textarea id="log" class="form-control" rows="10" @bind="@_log" readonly />
                </div>
            </div>
		</div>
		<br /><br />
		<button type="button" class="btn btn-danger" @onclick="ClearLog">@Localizer["Clear"]</button>
	</TabPanel>
</TabStrip>
<br /><br />

@code {
	public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Host;

	private string _version = string.Empty;
	private string _clrversion = string.Empty;
	private string _osversion = string.Empty;
	private string _machinename = string.Empty;
	private string _ipaddress = string.Empty;
	private string _environment = string.Empty;
	private string _contentrootpath = string.Empty;
	private string _webrootpath = string.Empty;
	private string _servertime = string.Empty;
	private string _tickcount = string.Empty;
	private string _workingset = string.Empty;
	private string _installationid = string.Empty;

	private string _detailederrors = string.Empty;
	private string _logginglevel = string.Empty;
	private string _notificationlevel = string.Empty;
	private string _swagger = string.Empty;
    private string _packageregistryurl = string.Empty;

	private string _log = string.Empty;

	protected override async Task OnInitializedAsync()
	{
		_version = Constants.Version;

		var systeminfo = await SystemService.GetSystemInfoAsync("environment");
		if (systeminfo != null)
		{
			_clrversion = systeminfo["CLRVersion"].ToString();
			_osversion = systeminfo["OSVersion"].ToString();
			_machinename = systeminfo["MachineName"].ToString();
			_ipaddress = systeminfo["IPAddress"].ToString();
			_environment = systeminfo["Environment"].ToString();
			_contentrootpath = systeminfo["ContentRootPath"].ToString();
			_webrootpath = systeminfo["WebRootPath"].ToString();
			_servertime = systeminfo["ServerTime"].ToString() + " UTC";
			_tickcount = TimeSpan.FromMilliseconds(Convert.ToInt64(systeminfo["TickCount"].ToString())).ToString();
			_workingset = (Convert.ToInt64(systeminfo["WorkingSet"].ToString()) / 1000000).ToString() + " MB";
		}

		systeminfo = await SystemService.GetSystemInfoAsync("configuration");
		if (systeminfo != null)
		{
			_installationid = systeminfo["InstallationId"].ToString();
			_detailederrors = systeminfo["DetailedErrors"].ToString();
			_logginglevel = systeminfo["Logging:LogLevel:Default"].ToString();
			_notificationlevel = systeminfo["Logging:LogLevel:Notify"].ToString();
			_swagger = systeminfo["UseSwagger"].ToString();
            _packageregistryurl = systeminfo["PackageRegistryUrl"].ToString();
		}

		systeminfo = await SystemService.GetSystemInfoAsync("log");
		if (systeminfo != null)
		{
			_log = systeminfo["Log"].ToString();
		}
	}

	private async Task SaveConfig()
	{
		try
		{
			var settings = new Dictionary<string, object>();
			settings.Add("DetailedErrors", _detailederrors);
			settings.Add("Logging:LogLevel:Default", _logginglevel);
			settings.Add("Logging:LogLevel:Notify", _notificationlevel);
			settings.Add("UseSwagger", _swagger);
			settings.Add("PackageRegistryUrl", _packageregistryurl);
			await SystemService.UpdateSystemInfoAsync(settings);
			AddModuleMessage(Localizer["Success.UpdateConfig.Restart"], MessageType.Success);
		}
		catch (Exception ex)
		{
			await logger.LogError(ex, "Error Saving Configuration");
			AddModuleMessage(Localizer["Error.UpdateConfig"], MessageType.Error);
		}
	}

	private async Task ClearLog()
	{
		try
		{
			var settings = new Dictionary<string, object>();
			settings.Add("clearlog", "true");
			await SystemService.UpdateSystemInfoAsync(settings);
			_log = string.Empty;
			AddModuleMessage(Localizer["Success.ClearLog"], MessageType.Success);
		}
		catch (Exception ex)
		{
			await logger.LogError(ex, "Error Clearing Log");
			AddModuleMessage(Localizer["Error.ClearLog"], MessageType.Error);
		}
	}

    private async Task RestartApplication()
    {
        try
        {
            ShowProgressIndicator();
            var interop = new Interop(JSRuntime);
            await interop.RedirectBrowser(NavigateUrl(""), 20);
            await InstallationService.RestartAsync();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Restarting Application");
        }
    }
}